package cn.niit.controller;

import cn.niit.entity.Resource;
import cn.niit.entity.query.ResourceQuery;
import cn.niit.service.ResourceService;
import com.github.pagehelper.PageInfo;
import io.swagger.models.Response;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.shiro.web.filter.authc.UserFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Controller
@Slf4j
@RequestMapping("/resource")
public class ResourceController {

    @Autowired
    private ResourceService resourceService;

    @GetMapping("/query")
    public String resource(Model model, ResourceQuery query){
        PageInfo<Resource> PageInfo= resourceService.listUserByName(query);
        model.addAttribute("page",PageInfo);
//        List<Resource> resources = resourceService.list();
//        model.addAttribute("page",resources);
        return "resource";
    }

    @GetMapping("/addResource")
    public String addResource(Resource resource){
//        resourceService.add(resource);
        return "addResource";
    }



    @GetMapping("/upload")
    public String getmapping(){

        return "redirect:/resource/query";
    }

    @GetMapping("/edit/{id}")
    public String toedit(@PathVariable("id") Integer id, Model model) {
        model.addAttribute("resource", resourceService.queryResourceById(id));
        return "editResource";
    }

    @PostMapping("/edit")
    public String edit(Resource resource, Integer id, Model model, RedirectAttributes attributes){
        boolean b = resourceService.updateResource(resource);
        if (b){
            attributes.addFlashAttribute("message", "更新成功");
            return "redirect:/resource/query";
        }else {
            attributes.addFlashAttribute("message", "更新失败");
            return "redirect:/resource/query";
        }

    }
    @GetMapping("/delete/{id}")
    public String deleteResource(@PathVariable("id") Integer id, Model model){
        System.out.println(id);
        boolean b = resourceService.deleteById(id);
        return "redirect:/resource/query";
    }

    /**
     * 文件的上传
     * @param resource
     * @param title
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/upload")
    public String upload(Resource resource, @RequestParam("title")String title,
                         @RequestPart("file") MultipartFile file) throws IOException {
        log.info("上传信息: + title={},  file={}", title, file.getSize());
        String oldfileName = file.getOriginalFilename(); //原始文件名称
        String extension = "." + FilenameUtils.getExtension(file.getOriginalFilename()); //获取文件后缀
        String newFileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+ UUID.randomUUID().toString().replace("-","")+extension; // 新文件名称
        long size = file.getSize(); //文件大小
        String type = file.getContentType();//文件类型

        //根据日期生成目录，动态
        //FIXME 该目录不能是工程地下的文件夹
        String realpath =ResourceUtils.getURL("D:").getPath()+ "/static/files"; //上传文件所保存的目录

        String dateFromat =  new SimpleDateFormat("yyyy-MM-dd").format(new Date()); //文件上传日期，用于文件上传子目录
        String dateDirPath = realpath + "/" + dateFromat;
        File dateDir = new File(dateDirPath);
        if (!dateDir.exists()) {
            dateDir.mkdir();
        }
        //处理文件上传
        file.transferTo(new File(dateDir,newFileName));
        //将文件信息放入数据库中
        resource.setOldfilename(oldfileName);
        resource.setNewfilename(newFileName);
        resource.setExt(extension);
        resource.setPath("/files/" + dateFromat);
        resourceService.add(resource);
      /*  if (!file.isEmpty()) {
            String originalFilename = file.getOriginalFilename();
            file.transferTo(new File("D:\\resource\\" + originalFilename));
        }*/
      /*  if (files.length > 0) {
            for (MultipartFile file1 : files) {
                if (!file1.isEmpty()) {
                    String originalFilename = file1.getOriginalFilename();
                    file1.transferTo(new File("F:\\pic\\" + originalFilename));
                }
            }
        }*/
        return "redirect:/resource/query";
    }

    @GetMapping("download/{id}")
    public void download( @PathVariable("id") String id, HttpServletResponse response) throws IOException {
        //获取文件信息
        Resource userFile = resourceService.findById(id);
        //根据文件名字和文件存储路径获取文件输入流
        String realPath =  ResourceUtils.getURL("D:").getPath()+"/static"+userFile.getPath();
        //获取文件输入流
        FileInputStream is = new FileInputStream(new File(realPath,userFile.getNewfilename()));
        //附件下载
        response.setHeader("content-disposition","attachment;filename="+ URLEncoder.encode(userFile.getOldfilename(),"UTF-8"));

        //获取响应输出流
        ServletOutputStream os = response.getOutputStream();
        //文件拷贝
        IOUtils.copy(is,os);
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(os);
    }
}
